package com.zbangmall.wechat;


import com.alibaba.fastjson.JSONObject;
import com.zbangmall.util.common.HttpUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.Test;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WechatShareClient {
	public static Log log = LogFactory.getLog(Test.class);

	//字节数组转换为十六进制字符串
	private static String byteToHex(final byte[] hash) {
		java.util.Formatter formatter = new java.util.Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	//生成随机字符串
	private static String createNonceStr() {
		return UUID.randomUUID().toString();
	}

	//生成时间戳
	private static String createTimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	public void getTest() throws Exception {
		JSONObject resultAccessToken = getAccessToken();
		String     accessToken       = resultAccessToken.getString("access_token");
		System.out.println(accessToken);
		JSONObject          resultJsApiTicket = getJsApiTicket(accessToken);
		String              jsapiTicket       = resultJsApiTicket.getString("ticket");
		Map<String, String> map               = makeWXTicket(jsapiTicket, "https://www.zbangmall.com/1.html");
		for (Map.Entry<String, String> entry : map.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
	}

	//获取accessToken
	private JSONObject getAccessToken() {
		String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
		String requestUrl     = accessTokenUrl.replace("APPID", WechatLoginClient.getAppid()).replace("APPSECRET", WechatLoginClient.getAppSecret());
		log.info("getAccessToken.requestUrl====>" + requestUrl);
		JSONObject result = HttpUtil.doGet(requestUrl);
		return result;
	}

	//获取ticket
	private JSONObject getJsApiTicket(String accessToken) {
		String apiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&convert=jsapi";
		String requestUrl   = apiTicketUrl.replace("ACCESS_TOKEN", accessToken);
		log.info("getJsApiTicket.requestUrl====>" + requestUrl);
		JSONObject result = HttpUtil.doGet(requestUrl);
		return result;
	}

	//生成微信权限验证的参数
	public Map<String, String> makeWXTicket(String jsApiTicket, String url) {
		Map<String, String> ret       = new HashMap<String, String>();
		String              nonceStr  = createNonceStr();
		String              timestamp = createTimestamp();
		String              string1;
		String              signature = "";

		//注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsApiTicket +
				"&noncestr=" + nonceStr +
				"&timestamp=" + timestamp +
				"&url=" + url;
		log.info("String1=====>" + string1);
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
			log.info("signature=====>" + signature);
		} catch (NoSuchAlgorithmException e) {
			log.error("WeChatController.makeWXTicket=====Start");
			log.error(e.getMessage(), e);
			log.error("WeChatController.makeWXTicket=====End");
		} catch (UnsupportedEncodingException e) {
			log.error("WeChatController.makeWXTicket=====Start");
			log.error(e.getMessage(), e);
			log.error("WeChatController.makeWXTicket=====End");
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsApiTicket);
		ret.put("nonceStr", nonceStr);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		ret.put("appid", WechatLoginClient.getAppid());

		return ret;
	}

}
